package com.it.day2;

import lombok.AllArgsConstructor;
import lombok.Getter;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: CompletableFutureNetMallDemo
 * Description: 对外网站比价需求
 *
 *  需求：统计各大电商网站同一本书的价格。
 *
 * @Author: csx
 * @Create: 2025/5/8 - 14:27
 * @version: v1.0
 */
public class CompletableFutureNetMallDemo {
    static List<NetMall> list = List.of(
            new NetMall("jd"),
            new NetMall("taobao"),
            new NetMall("pdd")
    );

    public static List<String> getPriceByStep(List<NetMall> list, String productName){
        return list.stream().map(netMall -> String.format("%s 网站 %s book price：%.2f", netMall.getMallName(), productName, netMall.calcPrice(productName)))
                .toList();
    }

    public static List<String> getPriceByASync(List<NetMall> list, String productName){
        return list.stream()
                .map(netMall -> CompletableFuture.supplyAsync(() -> String.format("%s 网站 %s book price：%.2f", netMall.getMallName(), productName, netMall.calcPrice(productName))))
                .toList()
                .stream().map(CompletableFuture::join)
                .toList();
    }

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        List<String> list1 = getPriceByStep(list, "mysql");
        for (String s : list1) {
            System.out.println(s);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("-----耗时：" + (endTime - startTime) + " 毫秒！");

        long startTime2 = System.currentTimeMillis();
        List<String> list2 = getPriceByASync(list, "mysql");
        for (String s : list2) {
            System.out.println(s);
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("-----耗时：" + (endTime2 - startTime2) + " 毫秒！");
    }
}

@AllArgsConstructor
class NetMall{
    @Getter
    private String mallName;    //电商网站名

    //模拟爬虫，根据书名返回价格
    public double calcPrice(String productName) {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}





















